/**
 * @description 新闻详情页面对应的属性组件
 */

import React, { useEffect, useMemo, useState, useContext, useRef } from 'react'
import { Collapse, Form, Select, Input, Radio, Tooltip } from 'antd';
import {
  InfoCircleOutlined
} from '@ant-design/icons';

import { replaceObjectStyle, replaceCssStyle } from '@/utils/style';
import { setAttrForm } from '@/utils/AttrForm';
import { debounce } from 'lodash-es'
import { copyTemplate, pasteTemplate, copyBlock, pasteBlock } from '@/utils/clipboard';
import { FlagOptions, iconTextReg } from '@/utils/Const';
import { UpdateContext } from '@/store/updateContext';

import StyleWrapper from '@/components/StylesWrapper';
import CssEdit from '@/components/Monaco/CssEidt';
import AttrHeaderBtn from './Components/AttrHeaderBtn';
import AttrExtra from './Components/AttrExtra';


function ForumdetailAtrr({ template2, onConfigEvent, setIsRightAttr, actKey }) {

  const updateCtx = useContext(UpdateContext)
  const [form] = Form.useForm()
  // css编辑器
  const [open, setOpen] = useState(false)
  // css编辑器实例
  const cssEditRef = useRef()

  // 更新style样式文件
  let upateStyleEvent = (keys) => {
    let divData = Object.assign({}, form.getFieldValue(keys))

    // keys数组的最后一项，就是key
    let key = keys.at(-1)
    replaceObjectStyle(actKey, key, divData)
  }

  // 组件css变化
  let cssChange = (value) => {
    form.setFieldValue('css', value)
    replaceCssStyle(actKey, value)
  }

  // input组件onChange事件防抖
  let onConfigEvent_debounce = debounce((keys, newValue) => {
    onConfigEvent(keys, newValue)
  }, 300)


  // 图标输入框变化事件，比普通输入框，多一个字符串转化逻辑
  let iconEvent = (keys, value) => {

    // 去除 空格、<、/> 
    let newValue = value.replace(iconTextReg, '')
    form.setFieldValue(keys, newValue)

    onConfigEvent(keys, newValue)
  }

  // 头部按钮事件
  let handleHeaderEvent = (key) => {
    switch (key) {

      // 打开组件css编辑
      case 'css':
        setOpen(true)
        break;

      // 复制模板
      case 'copy':
        copyTemplate(actKey, [], form)
        break;

      // 黏贴模板
      case 'paste':
        pasteTemplate(form, onConfigEvent, actKey)
        updateCtx.setUpdateFlag(pre => !pre)

        // 修改css编辑器的值
        cssEditRef.current.setValue(form.getFieldValue('css'))
        break;

      // 切换位置
      case 'position':
        setIsRightAttr((isRight) => !isRight)
        break;

      default:
        break;
    }
  }

  // 属性栏右上角按钮事件
  let handleAttrEvent = (eventKey, blockKey, paramKeys, classKey) => {
    switch (eventKey) {

      // 复制模块
      case 'copy':
        copyBlock(actKey, blockKey, paramKeys, classKey, form)
        break;

      // 黏贴模块
      case 'paste':
        pasteBlock(actKey, blockKey, paramKeys, classKey, form, onConfigEvent)
        updateCtx.setUpdateFlag(pre => !pre)
        break;


      default:
        break;
    }
  }

  // -----------------------------------
  // 构造折叠面板的数据
  // -----------------------------------
  let items = useMemo(() => {

    let items = [
      {
        key: "page",
        label: "总盒子",
        children:
          <StyleWrapper form={form} preKeys={['page', 'default']} onStyleChange={() => upateStyleEvent(['page'])} />
      },
      {
        key: "header",
        label: "页面标题",
        extra: <AttrExtra onEvent={(eventKey) => handleAttrEvent(eventKey, 'pageTitle', ['header'], 'forumdetail')} />,
        children:
          <Collapse accordion items={[
            {
              key: "box",
              label: "盒子",
              children: <StyleWrapper form={form} preKeys={['header', 'forumdetail_box', 'default']} onStyleChange={() => upateStyleEvent(['header', 'forumdetail_box'])} />
            },
            {
              key: "title",
              label: "标题",
              children: <StyleWrapper form={form} preKeys={['header', 'forumdetail_title', 'default']} onStyleChange={() => upateStyleEvent(['header', 'forumdetail_title'])} />
            },
          ]} />
      },
      {
        key: "article",
        label: "文章详情",
        children:
          <Collapse accordion items={[
            {
              key: "box",
              label: "盒子",
              children: <StyleWrapper form={form} preKeys={['forumattr', 'forumattr_box', 'default']} onStyleChange={() => upateStyleEvent(['forumattr', 'forumattr_box'])} />
            },
            {
              key: "title",
              label: "标题",
              children: <StyleWrapper form={form} preKeys={['forumattr', 'forumattr_title', 'default']} onStyleChange={() => upateStyleEvent(['forumattr', 'forumattr_title'])} />
            },
            {
              key: "info",
              label: "属性",
              children:
                <>
                  <Form.Item
                    label="图标开关"
                    name={['forumattr', 'base', 'iconFlag']}
                  >
                    <Radio.Group
                      options={FlagOptions}
                      onChange={(e) => onConfigEvent(['forumattr', 'base', 'iconFlag'], e.target.value)}
                      optionType="button"
                      buttonStyle="solid"
                    />
                  </Form.Item>

                  <Form.Item
                    label="标签开关"
                    name={['forumattr', 'base', 'labelFlag']}
                  >
                    <Radio.Group
                      options={FlagOptions}
                      onChange={(e) => onConfigEvent(['forumattr', 'base', 'labelFlag'], e.target.value)}
                      optionType="button"
                      buttonStyle="solid"
                    />
                  </Form.Item>

                  <Collapse accordion items={[
                    {
                      key: "box",
                      label: "盒子",
                      children: <StyleWrapper form={form} preKeys={['forumattr', 'forumattr_info', 'default']} onStyleChange={() => upateStyleEvent(['forumattr', 'forumattr_info'])} />
                    },
                    {
                      key: "time",
                      label: "时间",
                      children: <StyleWrapper form={form} preKeys={['forumattr', 'forumattr_time', 'default']} onStyleChange={() => upateStyleEvent(['forumattr', 'forumattr_time'])} />
                    },
                    {
                      key: "publisher",
                      label: "发布人",
                      children: <StyleWrapper form={form} preKeys={['forumattr', 'forumattr_publisher', 'default']} onStyleChange={() => upateStyleEvent(['forumattr', 'forumattr_publisher'])} />
                    },

                  ]} />
                </>
            },
            {
              key: "operate",
              label: "点赞/收藏",
              extra: <AttrExtra onEvent={(eventKey) => handleAttrEvent(eventKey, 'operate', ['operate'], 'forumattr')} />,
              children:
                <>
                  <Collapse accordion items={[
                    {
                      key: "icon",
                      label: "图标",
                      children: <>
                        <Form.Item
                          label="点赞"
                          name={['operate', 'base', 'thumbsup_icon']}
                        >
                          <Input
                            onChange={(e) => iconEvent(['operate', 'base', 'thumbsup_icon'], e.target.value)}
                          />
                        </Form.Item>

                        <Form.Item
                          label="已点赞"
                          name={['operate', 'base', 'thumbsuped_icon']}
                        >
                          <Input
                            onChange={(e) => iconEvent(['thumbsup', 'base', 'thumbsuped_icon'], e.target.value)}
                          />
                        </Form.Item>

                        <Form.Item
                          label="收藏"
                          name={['operate', 'base', 'storeup_icon']}
                        >
                          <Input
                            onChange={(e) => iconEvent(['operate', 'base', 'storeup_icon'], e.target.value)}
                          />
                        </Form.Item>

                        <Form.Item
                          label="已收藏"
                          name={['operate', 'base', 'storeuped_icon']}
                        >
                          <Input
                            onChange={(e) => iconEvent(['operate', 'base', 'storeuped_icon'], e.target.value)}
                          />
                        </Form.Item>
                      </>
                    },
                    {
                      key: "box",
                      label: "盒子",
                      children: <StyleWrapper form={form} preKeys={['operate', 'forumattr_operate', 'default']} onStyleChange={() => upateStyleEvent(['operate', 'forumattr_operate'])} />
                    },
                    {
                      key: "thumbs",
                      label: "点赞",
                      children: <StyleWrapper form={form} preKeys={['operate', 'forumattr_thumbs', 'default']} onStyleChange={() => upateStyleEvent(['operate', 'forumattr_thumbs'])} />
                    },
                    {
                      key: "thumbs-hover",
                      label: "点赞-悬浮",
                      children: <StyleWrapper form={form} preKeys={['operate', 'forumattr_thumbs', 'hover']} onStyleChange={() => upateStyleEvent(['operate', 'forumattr_thumbs'])} />
                    },
                    {
                      key: "store",
                      label: "收藏",
                      children: <StyleWrapper form={form} preKeys={['operate', 'forumattr_storeup', 'default']} onStyleChange={() => upateStyleEvent(['operate', 'forumattr_storeup'])} />
                    },
                    {
                      key: "store-hover",
                      label: "收藏-悬浮",
                      children: <StyleWrapper form={form} preKeys={['operate', 'forumattr_storeup', 'hover']} onStyleChange={() => upateStyleEvent(['operate', 'forumattr_storeup'])} />
                    },
                  ]} />
                </>
            },
            {
              key: "content",
              label: "内容",
              children: <StyleWrapper form={form} preKeys={['forumattr', 'forumattr_content', 'default']} onStyleChange={() => upateStyleEvent(['forumattr', 'forumattr_content'])} />
            },
          ]} />
      },
      {
        key: "tab",
        label: <Tooltip title='在【详情】-【商品详情】配置'>
          评论
          <InfoCircleOutlined className='tooltip-icon' />
        </Tooltip>,
        children: null
      },
    ]
    return items
  }, [
    updateCtx.updateFlag
  ])


  useEffect(() => {
    setAttrForm(form)
  }, [form])

  return (
    <>
      <Form
        name='forumdetail'
        form={form}
        initialValues={template2}
        labelCol={{
          span: 8,
        }
        }
        autoComplete="off"
        spellCheck="false"
      >

        {/* 按钮区域 */}
        <AttrHeaderBtn onClickEvent={handleHeaderEvent} />

        {/* 对象形式的样式编辑 */}
        <Collapse accordion destroyInactivePanel size='middle' items={items} />

      </Form>

      {/* 字符串形式的样式编辑 */}
      <CssEdit value={template2.css} open={open} onValueChange={cssChange} setOpen={setOpen} ref={cssEditRef} />

    </>
  )
}
export default React.memo(ForumdetailAtrr) 